<template>
  <main>
    <!-- <hr data-am-widget="divider" style="" class="am-divider am-divider-default" />

    <p>已选择分类</p>
    <a class="selected-tag" href="javascript:;" v-for="(tag, index) in selected" :key="index" @click="removeTag(index)">
      <am-tag
        closeable
        @tag-remove="removeTag(index)">
        {{ tag.name }}
      </am-tag>
    </a>

    <hr data-am-widget="divider" style="" class="am-divider am-divider-default" /> -->

    <p>选择分类</p>
    <am-list :static="true">
      <!-- 主分类 -->
      <am-list-item v-for="(tagMain, index) in tags" :key="index">
        <!-- 子分类 -->
        {{ tagMain.main.name }}：
        <a :class="[{'disabled-tag': tag.disabled}, 'tag']" href="javascript:;"
          v-for="(tag, index) in tagMain.sub" :key="index" @click="select(tagMain.sub, tag)">
          <am-tag :color="tag.color">{{ tag.name }}</am-tag>
        </a>
      </am-list-item>
    </am-list>
  </main>
</template>

<script>
export default {
  name: 'tags',
  data() {
    return {
      selected: this.worksTags
    }
  },
  computed: {
    tags() {
      return this.$store.state.tags;
    }
  },
  methods: {
    ready() {
    },
    select(tagMain, tag) {
      /**
       * 这里设置tags的属性留意几个问题
       * 1. computed没有setter，其属性有
       * 2. 而且确定没有影响到state
       * 
       * 对tags是直接使用reduce似乎不对，还是对其下属性进行设置
       */


      if(!this.selected.includes(tag)) {
        this.selected.push(tag);
        this.$set(tag, 'color', 'primary');
        // 使其它subtags失效
        tagMain.forEach(item => {
          if(item !== tag) {// 禁用
            this.$set(item, 'disabled', true)
          }
        });
      } else {
        this.selected.splice(this.selected.findIndex(t => t.id === tag.id), 1);
        tag.color = void 0;
        // 恢复所有subtabs
        tagMain.forEach(item => {
          item.disabled = false;
        });
      }
    }
  },
  watch: {
    selected(val) {
      // let tem = val.map(tag => tag.id);
      this.$emit('update:worksTags', val);
    }
  },
  props: {
    worksTags: {
      type: Array,
      default() {
        return [];
      },
    }
  },
  mounted() {
    this.ready();
  }
}
</script>

<style scoped>
.tag {
  display: inline-block !important;
  margin: 0 5px !important;
  padding: 0 !important;
}
.selected-tag {
  display: inline-block !important;
  margin: 5px !important;
  padding: 0 !important;
}
.disabled-tag {
  opacity: .5;
  pointer-events: none;
}
</style>
